/*!
 * \file test_parser_interfaces_comprehensive.cpp
 * \project WonderTrader
 *
 * \author Wesley
 * \date 2024/12/01
 * 
 * \brief 行情解析接口综合测试
 * 
 * \details 该文件包含对WonderTrader行情解析接口的全面测试，包括：
 *          - IParserApi接口的完整功能测试
 *          - IParserSpi回调接口的测试
 *          - 行情数据处理流程测试
 *          - 连接管理和状态控制测试
 *          - 订阅管理和数据推送测试
 *          - 错误处理和异常恢复测试
 *          - 性能和并发测试
 *          - 完整的工作流程测试
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <thread>
#include <chrono>
#include <atomic>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <mutex>
#include <condition_variable>

#include "../../src/Includes/IParserApi.h"
#include "../../src/Includes/WTSTypes.h"
#include "../../src/Includes/WTSObject.hpp"
#include "../../src/Includes/WTSCollection.hpp"
#include "../../src/Includes/WTSVariant.hpp"

USING_NS_WTP;

/*!
 * \brief Mock基础数据管理器
 * 
 * \details 模拟基础数据管理器，用于测试行情解析器的基础数据依赖
 */
class MockIBaseDataMgr : public IBaseDataMgr {
public:
    MOCK_METHOD(WTSCommodityInfo*, getCommodity, (const char* exchg, const char* pid), (override));
    MOCK_METHOD(WTSCommodityInfo*, getCommodity, (const char* stdCode), (override));
    MOCK_METHOD(WTSSessionInfo*, getSession, (const char* sid), (override));
    MOCK_METHOD(WTSSessionInfo*, getSessionByCode, (const char* stdCode), (override));
    MOCK_METHOD(WTSContractInfo*, getContract, (const char* stdCode), (override));
    MOCK_METHOD(WTSContractInfo*, getContract, (const char* exchg, const char* code), (override));
    MOCK_METHOD(WTSArray*, getContracts, (const char* exchg), (override));
    MOCK_METHOD(WTSArray*, getAllContracts, (), (override));
    MOCK_METHOD(bool, isHoliday, (const char* pid, uint32_t uDate, bool isTpl), (override));
    MOCK_METHOD(uint32_t, calcTradingDate, (const char* pid, uint32_t uDate, uint32_t uTime, bool isSession), (override));
    MOCK_METHOD(uint64_t, getBoundaryTime, (const char* stdCode, uint32_t tDate, bool isStart, bool isSession), (override));
    MOCK_METHOD(void, release, (), (override));
};

/*!
 * \brief Mock行情解析器回调接口
 * 
 * \details 模拟行情解析器回调接口，用于测试行情数据的接收和处理
 */
class MockIParserSpi : public IParserSpi {
public:
    MOCK_METHOD(void, handleSymbolList, (const WTSArray* aySymbols), (override));
    MOCK_METHOD(void, handleQuote, (WTSTickData *quote, uint32_t procFlag), (override));
    MOCK_METHOD(void, handleOrderQueue, (WTSOrdQueData* ordQueData), (override));
    MOCK_METHOD(void, handleOrderDetail, (WTSOrdDtlData* ordDetailData), (override));
    MOCK_METHOD(void, handleTransaction, (WTSTransData* transData), (override));
    MOCK_METHOD(void, handleParserLog, (WTSLogLevel ll, const char* message), (override));
    MOCK_METHOD(IBaseDataMgr*, getBaseDataMgr, (), (override));
};

/*!
 * \brief Mock行情解析器API实现
 * 
 * \details 模拟行情解析器API，用于测试各种行情解析场景
 */
class MockIParserApi : public IParserApi {
private:
    bool connected_;
    IParserSpi* spi_;
    std::set<std::string> subscribed_codes_;
    mutable std::mutex mutex_;
    std::atomic<bool> running_;
    std::thread worker_thread_;
    std::queue<std::function<void()>> task_queue_;
    std::condition_variable cv_;

public:
    MockIParserApi() : connected_(false), spi_(nullptr), running_(false) {}
    
    virtual ~MockIParserApi() {
        if (running_) {
            disconnect();
        }
    }

    MOCK_METHOD(bool, init, (WTSVariant* config), (override));
    MOCK_METHOD(void, release, (), (override));
    
    // 实际实现连接管理功能用于测试
    virtual bool connect() override {
        std::lock_guard<std::mutex> lock(mutex_);
        if (!connected_) {
            connected_ = true;
            running_ = true;
            
            // 启动工作线程模拟异步处理
            worker_thread_ = std::thread([this]() {
                while (running_) {
                    std::unique_lock<std::mutex> lock(mutex_);
                    cv_.wait_for(lock, std::chrono::milliseconds(100), [this]() {
                        return !task_queue_.empty() || !running_;
                    });
                    
                    while (!task_queue_.empty() && running_) {
                        auto task = task_queue_.front();
                        task_queue_.pop();
                        lock.unlock();
                        task();
                        lock.lock();
                    }
                }
            });
            
            // 模拟连接成功后的初始化
            if (spi_) {
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
                // 可以在这里触发连接成功的回调
            }
        }
        return connected_;
    }
    
    virtual bool disconnect() override {
        std::lock_guard<std::mutex> lock(mutex_);
        if (connected_) {
            running_ = false;
            cv_.notify_all();
            
            if (worker_thread_.joinable()) {
                mutex_.unlock();
                worker_thread_.join();
                mutex_.lock();
            }
            
            connected_ = false;
            subscribed_codes_.clear();
        }
        return true;
    }
    
    virtual bool isConnected() override {
        std::lock_guard<std::mutex> lock(mutex_);
        return connected_;
    }
    
    virtual void subscribe(const CodeSet& setCodes) override {
        std::lock_guard<std::mutex> lock(mutex_);
        if (connected_) {
            for (const auto& code : setCodes) {
                subscribed_codes_.insert(code);
            }
        }
    }
    
    virtual void unsubscribe(const CodeSet& setCodes) override {
        std::lock_guard<std::mutex> lock(mutex_);
        for (const auto& code : setCodes) {
            subscribed_codes_.erase(code);
        }
    }
    
    virtual void registerSpi(IParserSpi* listener) override {
        std::lock_guard<std::mutex> lock(mutex_);
        spi_ = listener;
    }
    
    // 测试辅助方法
    void simulateQuoteData(const std::string& code, double price) {
        if (!connected_ || !spi_) return;
        
        std::lock_guard<std::mutex> lock(mutex_);
        if (subscribed_codes_.find(code) != subscribed_codes_.end()) {
            task_queue_.push([this, code, price]() {
                // 创建模拟的tick数据
                WTSTickData* tick = WTSTickData::create(code.c_str());
                if (tick) {
                    tick->setPrice(price);
                    tick->setVolume(100);
                    tick->setTurnover(price * 100);
                    tick->setOpenInterest(1000);
                    
                    spi_->handleQuote(tick, 0);
                    tick->release();
                }
            });
            cv_.notify_one();
        }
    }
    
    size_t getSubscribedCount() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return subscribed_codes_.size();
    }
    
    bool isSubscribed(const std::string& code) const {
        std::lock_guard<std::mutex> lock(mutex_);
        return subscribed_codes_.find(code) != subscribed_codes_.end();
    }
};

/*!
 * \brief 行情解析接口综合测试夹具类
 * 
 * \details 提供行情解析接口测试的基础设施和通用功能
 */
class ParserInterfacesTest : public ::testing::Test {
protected:
    void SetUp() override {
        mock_base_data_mgr_ = std::make_unique<MockIBaseDataMgr>();
        mock_parser_spi_ = std::make_unique<MockIParserSpi>();
        mock_parser_api_ = std::make_unique<MockIParserApi>();
        
        // 设置基础数据管理器返回
        EXPECT_CALL(*mock_parser_spi_, getBaseDataMgr())
            .WillRepeatedly(::testing::Return(mock_base_data_mgr_.get()));
    }
    
    void TearDown() override {
        if (mock_parser_api_ && mock_parser_api_->isConnected()) {
            mock_parser_api_->disconnect();
        }
    }
    
    std::unique_ptr<MockIBaseDataMgr> mock_base_data_mgr_;
    std::unique_ptr<MockIParserSpi> mock_parser_spi_;
    std::unique_ptr<MockIParserApi> mock_parser_api_;
};

/*!
 * \brief 测试行情解析器初始化
 * 验证行情解析器的基本初始化功能
 */
TEST_F(ParserInterfacesTest, TestParserInitialization) {
    // 创建配置参数
    WTSVariant* config = WTSVariant::createObject();
    config->append("host", "127.0.0.1", false);
    config->append("port", 9999, false);
    config->append("user", "testuser", false);
    config->append("pass", "testpass", false);
    
    // 测试初始化
    EXPECT_CALL(*mock_parser_api_, init(::testing::_))
        .WillOnce(::testing::Return(true));
    
    EXPECT_TRUE(mock_parser_api_->init(config));
    
    config->release();
}

/*!
 * \brief 测试行情解析器连接管理
 * 验证连接建立、断开和状态检查功能
 */
TEST_F(ParserInterfacesTest, TestConnectionManagement) {
    // 注册回调接口
    mock_parser_api_->registerSpi(mock_parser_spi_.get());
    
    // 测试初始状态
    EXPECT_FALSE(mock_parser_api_->isConnected());
    
    // 测试连接
    EXPECT_TRUE(mock_parser_api_->connect());
    EXPECT_TRUE(mock_parser_api_->isConnected());
    
    // 测试重复连接
    EXPECT_TRUE(mock_parser_api_->connect());
    EXPECT_TRUE(mock_parser_api_->isConnected());
    
    // 测试断开连接
    EXPECT_TRUE(mock_parser_api_->disconnect());
    EXPECT_FALSE(mock_parser_api_->isConnected());
    
    // 测试重复断开
    EXPECT_TRUE(mock_parser_api_->disconnect());
    EXPECT_FALSE(mock_parser_api_->isConnected());
}

/*!
 * \brief 测试订阅管理功能
 * 验证合约订阅和退订功能
 */
TEST_F(ParserInterfacesTest, TestSubscriptionManagement) {
    mock_parser_api_->registerSpi(mock_parser_spi_.get());
    ASSERT_TRUE(mock_parser_api_->connect());
    
    // 准备订阅代码集合
    CodeSet codes_to_subscribe;
    codes_to_subscribe.insert("SHFE.au2501");
    codes_to_subscribe.insert("SHFE.ag2501");
    codes_to_subscribe.insert("DCE.m2501");
    
    // 测试订阅
    mock_parser_api_->subscribe(codes_to_subscribe);
    EXPECT_EQ(mock_parser_api_->getSubscribedCount(), 3);
    EXPECT_TRUE(mock_parser_api_->isSubscribed("SHFE.au2501"));
    EXPECT_TRUE(mock_parser_api_->isSubscribed("SHFE.ag2501"));
    EXPECT_TRUE(mock_parser_api_->isSubscribed("DCE.m2501"));
    
    // 测试部分退订
    CodeSet codes_to_unsubscribe;
    codes_to_unsubscribe.insert("SHFE.ag2501");
    mock_parser_api_->unsubscribe(codes_to_unsubscribe);
    
    EXPECT_EQ(mock_parser_api_->getSubscribedCount(), 2);
    EXPECT_TRUE(mock_parser_api_->isSubscribed("SHFE.au2501"));
    EXPECT_FALSE(mock_parser_api_->isSubscribed("SHFE.ag2501"));
    EXPECT_TRUE(mock_parser_api_->isSubscribed("DCE.m2501"));
    
    // 测试全部退订
    mock_parser_api_->unsubscribe(codes_to_subscribe);
    EXPECT_EQ(mock_parser_api_->getSubscribedCount(), 1);
    EXPECT_FALSE(mock_parser_api_->isSubscribed("SHFE.au2501"));
    EXPECT_TRUE(mock_parser_api_->isSubscribed("DCE.m2501"));
}

/*!
 * \brief 测试行情数据处理
 * 验证tick数据的接收和处理功能
 */
TEST_F(ParserInterfacesTest, TestQuoteDataHandling) {
    mock_parser_api_->registerSpi(mock_parser_spi_.get());
    ASSERT_TRUE(mock_parser_api_->connect());
    
    // 订阅合约
    CodeSet codes;
    codes.insert("SHFE.au2501");
    mock_parser_api_->subscribe(codes);
    
    // 设置期望的回调
    EXPECT_CALL(*mock_parser_spi_, handleQuote(::testing::_, ::testing::_))
        .Times(::testing::AtLeast(1))
        .WillRepeatedly([](WTSTickData* quote, uint32_t procFlag) {
            EXPECT_NE(quote, nullptr);
            EXPECT_GT(quote->price(), 0);
            EXPECT_GT(quote->volume(), 0);
        });
    
    // 模拟行情数据
    mock_parser_api_->simulateQuoteData("SHFE.au2501", 380.50);
    
    // 等待异步处理完成
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    
    // 测试未订阅合约的数据不会被处理
    mock_parser_api_->simulateQuoteData("SHFE.ag2501", 4500.0);
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

/*!
 * \brief 测试回调接口功能
 * 验证各种回调接口的调用
 */
TEST_F(ParserInterfacesTest, TestCallbackInterfaces) {
    // 测试符号列表处理
    WTSArray* symbols = WTSArray::create();
    symbols->append(WTSString::create("SHFE.au2501"), false);
    symbols->append(WTSString::create("SHFE.ag2501"), false);
    
    EXPECT_CALL(*mock_parser_spi_, handleSymbolList(::testing::_))
        .Times(1)
        .WillOnce([](const WTSArray* aySymbols) {
            EXPECT_NE(aySymbols, nullptr);
            EXPECT_GT(aySymbols->size(), 0);
        });
    
    mock_parser_spi_->handleSymbolList(symbols);
    symbols->release();
    
    // 测试日志处理
    EXPECT_CALL(*mock_parser_spi_, handleParserLog(::testing::_, ::testing::_))
        .Times(1)
        .WillOnce([](WTSLogLevel ll, const char* message) {
            EXPECT_NE(message, nullptr);
            EXPECT_GT(strlen(message), 0);
        });
    
    mock_parser_spi_->handleParserLog(LL_INFO, "测试日志消息");
}

/*!
 * \brief 测试错误处理和异常恢复
 * 验证各种错误情况的处理
 */
TEST_F(ParserInterfacesTest, TestErrorHandlingAndRecovery) {
    // 测试未连接状态下的操作
    EXPECT_FALSE(mock_parser_api_->isConnected());
    
    CodeSet codes;
    codes.insert("SHFE.au2501");
    
    // 未连接状态下订阅应该不生效
    mock_parser_api_->subscribe(codes);
    EXPECT_EQ(mock_parser_api_->getSubscribedCount(), 0);
    
    // 连接后订阅应该生效
    ASSERT_TRUE(mock_parser_api_->connect());
    mock_parser_api_->subscribe(codes);
    EXPECT_EQ(mock_parser_api_->getSubscribedCount(), 1);
    
    // 测试连接断开后的状态
    ASSERT_TRUE(mock_parser_api_->disconnect());
    EXPECT_FALSE(mock_parser_api_->isConnected());
    EXPECT_EQ(mock_parser_api_->getSubscribedCount(), 0);
    
    // 测试重连
    ASSERT_TRUE(mock_parser_api_->connect());
    EXPECT_TRUE(mock_parser_api_->isConnected());
    
    // 重新订阅
    mock_parser_api_->subscribe(codes);
    EXPECT_EQ(mock_parser_api_->getSubscribedCount(), 1);
}

/*!
 * \brief 测试并发访问安全性
 * 验证多线程环境下的线程安全性
 */
TEST_F(ParserInterfacesTest, TestConcurrentAccess) {
    mock_parser_api_->registerSpi(mock_parser_spi_.get());
    ASSERT_TRUE(mock_parser_api_->connect());
    
    const int thread_count = 4;
    const int operations_per_thread = 100;
    std::vector<std::thread> threads;
    std::atomic<int> success_count(0);
    std::atomic<int> error_count(0);
    
    // 设置回调期望
    EXPECT_CALL(*mock_parser_spi_, handleQuote(::testing::_, ::testing::_))
        .Times(::testing::AtLeast(0))
        .WillRepeatedly([&success_count](WTSTickData* quote, uint32_t procFlag) {
            if (quote && quote->price() > 0) {
                success_count++;
            }
        });
    
    // 启动多个线程进行并发操作
    for (int i = 0; i < thread_count; ++i) {
        threads.emplace_back([this, i, operations_per_thread, &success_count, &error_count]() {
            try {
                for (int j = 0; j < operations_per_thread; ++j) {
                    std::string code = "TEST.code" + std::to_string(i * 1000 + j);
                    
                    // 订阅
                    CodeSet codes;
                    codes.insert(code);
                    mock_parser_api_->subscribe(codes);
                    
                    // 模拟数据
                    double price = 100.0 + i + j * 0.01;
                    mock_parser_api_->simulateQuoteData(code, price);
                    
                    // 短暂休眠
                    std::this_thread::sleep_for(std::chrono::microseconds(10));
                    
                    // 退订
                    mock_parser_api_->unsubscribe(codes);
                }
            } catch (const std::exception& e) {
                error_count++;
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 等待异步处理完成
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    
    // 验证结果
    EXPECT_EQ(error_count.load(), 0);
    EXPECT_GT(success_count.load(), 0);
    
    std::cout << "并发测试结果: 成功 " << success_count.load() 
              << " 次, 错误 " << error_count.load() << " 次" << std::endl;
}

/*!
 * \brief 测试性能基准
 * 验证行情解析器的性能表现
 */
TEST_F(ParserInterfacesTest, TestPerformanceBenchmark) {
    mock_parser_api_->registerSpi(mock_parser_spi_.get());
    ASSERT_TRUE(mock_parser_api_->connect());
    
    const int quote_count = 10000;
    std::atomic<int> processed_count(0);
    
    // 设置回调计数
    EXPECT_CALL(*mock_parser_spi_, handleQuote(::testing::_, ::testing::_))
        .Times(::testing::AtLeast(0))
        .WillRepeatedly([&processed_count](WTSTickData* quote, uint32_t procFlag) {
            processed_count++;
        });
    
    // 订阅测试合约
    CodeSet codes;
    codes.insert("PERF.test");
    mock_parser_api_->subscribe(codes);
    
    // 性能测试
    auto start_time = std::chrono::high_resolution_clock::now();
    
    for (int i = 0; i < quote_count; ++i) {
        double price = 100.0 + i * 0.01;
        mock_parser_api_->simulateQuoteData("PERF.test", price);
    }
    
    // 等待处理完成
    auto timeout = std::chrono::seconds(10);
    auto wait_start = std::chrono::high_resolution_clock::now();
    
    while (processed_count.load() < quote_count && 
           std::chrono::high_resolution_clock::now() - wait_start < timeout) {
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    
    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
    
    // 验证处理结果
    EXPECT_GT(processed_count.load(), quote_count * 0.8); // 允许80%的处理率
    
    double quotes_per_second = (double)processed_count.load() * 1000000.0 / duration.count();
    
    std::cout << "性能测试结果:" << std::endl;
    std::cout << "  处理行情数: " << processed_count.load() << "/" << quote_count << std::endl;
    std::cout << "  总耗时: " << duration.count() << " 微秒" << std::endl;
    std::cout << "  处理速度: " << static_cast<int>(quotes_per_second) << " 行情/秒" << std::endl;
    
    EXPECT_GT(quotes_per_second, 1000); // 期望至少1000行情/秒的处理能力
}

/*!
 * \brief 测试完整工作流程
 * 验证行情解析器的完整工作流程
 */
TEST_F(ParserInterfacesTest, TestCompleteWorkflow) {
    // 1. 初始化配置
    WTSVariant* config = WTSVariant::createObject();
    config->append("name", "test_parser", false);
    config->append("enabled", true, false);
    
    EXPECT_CALL(*mock_parser_api_, init(::testing::_))
        .WillOnce(::testing::Return(true));
    
    ASSERT_TRUE(mock_parser_api_->init(config));
    config->release();
    
    // 2. 注册回调接口
    mock_parser_api_->registerSpi(mock_parser_spi_.get());
    
    // 3. 建立连接
    ASSERT_TRUE(mock_parser_api_->connect());
    EXPECT_TRUE(mock_parser_api_->isConnected());
    
    // 4. 处理符号列表
    WTSArray* symbols = WTSArray::create();
    symbols->append(WTSString::create("SHFE.au2501"), false);
    symbols->append(WTSString::create("SHFE.ag2501"), false);
    symbols->append(WTSString::create("DCE.m2501"), false);
    
    EXPECT_CALL(*mock_parser_spi_, handleSymbolList(::testing::_))
        .Times(1);
    
    mock_parser_spi_->handleSymbolList(symbols);
    symbols->release();
    
    // 5. 订阅合约
    CodeSet subscription_codes;
    subscription_codes.insert("SHFE.au2501");
    subscription_codes.insert("SHFE.ag2501");
    subscription_codes.insert("DCE.m2501");
    
    mock_parser_api_->subscribe(subscription_codes);
    EXPECT_EQ(mock_parser_api_->getSubscribedCount(), 3);
    
    // 6. 处理行情数据
    std::atomic<int> quote_count(0);
    EXPECT_CALL(*mock_parser_spi_, handleQuote(::testing::_, ::testing::_))
        .Times(::testing::AtLeast(3))
        .WillRepeatedly([&quote_count](WTSTickData* quote, uint32_t procFlag) {
            quote_count++;
        });
    
    mock_parser_api_->simulateQuoteData("SHFE.au2501", 380.50);
    mock_parser_api_->simulateQuoteData("SHFE.ag2501", 4500.0);
    mock_parser_api_->simulateQuoteData("DCE.m2501", 3200.0);
    
    // 等待处理完成
    std::this_thread::sleep_for(std::chrono::milliseconds(300));
    
    // 7. 部分退订
    CodeSet unsubscribe_codes;
    unsubscribe_codes.insert("SHFE.ag2501");
    mock_parser_api_->unsubscribe(unsubscribe_codes);
    EXPECT_EQ(mock_parser_api_->getSubscribedCount(), 2);
    
    // 8. 继续处理数据
    mock_parser_api_->simulateQuoteData("SHFE.au2501", 381.00);
    mock_parser_api_->simulateQuoteData("SHFE.ag2501", 4510.0); // 应该被忽略
    mock_parser_api_->simulateQuoteData("DCE.m2501", 3210.0);
    
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    
    // 9. 断开连接
    ASSERT_TRUE(mock_parser_api_->disconnect());
    EXPECT_FALSE(mock_parser_api_->isConnected());
    EXPECT_EQ(mock_parser_api_->getSubscribedCount(), 0);
    
    // 10. 释放资源
    EXPECT_CALL(*mock_parser_api_, release())
        .Times(1);
    
    mock_parser_api_->release();
    
    // 验证整个流程
    EXPECT_GE(quote_count.load(), 3);
    
    std::cout << "完整工作流程测试通过:" << std::endl;
    std::cout << "  处理行情数: " << quote_count.load() << std::endl;
    std::cout << "  连接状态: " << (mock_parser_api_->isConnected() ? "已连接" : "已断开") << std::endl;
    std::cout << "  订阅数量: " << mock_parser_api_->getSubscribedCount() << std::endl;
}

/*!
 * \brief 测试资源管理和内存安全
 * 验证资源的正确分配和释放
 */
TEST_F(ParserInterfacesTest, TestResourceManagement) {
    const int iteration_count = 100;
    
    for (int i = 0; i < iteration_count; ++i) {
        // 创建临时解析器
        auto temp_parser = std::make_unique<MockIParserApi>();
        temp_parser->registerSpi(mock_parser_spi_.get());
        
        // 连接和断开
        ASSERT_TRUE(temp_parser->connect());
        EXPECT_TRUE(temp_parser->isConnected());
        
        // 订阅和退订
        CodeSet codes;
        codes.insert("TEST.resource" + std::to_string(i));
        temp_parser->subscribe(codes);
        EXPECT_EQ(temp_parser->getSubscribedCount(), 1);
        
        temp_parser->unsubscribe(codes);
        EXPECT_EQ(temp_parser->getSubscribedCount(), 0);
        
        // 断开连接
        ASSERT_TRUE(temp_parser->disconnect());
        EXPECT_FALSE(temp_parser->isConnected());
        
        // temp_parser会在作用域结束时自动析构
    }
    
    std::cout << "资源管理测试通过，完成 " << iteration_count << " 次迭代" << std::endl;
} 